package org.mili.ticketeer.report;

import org.apache.commons.io.FileUtils;
import org.mili.core.templating.TemplateStore;
import org.mili.ticketeer.dto.Group;
import org.mili.ticketeer.dto.Ticket;
import org.mili.ticketeer.service.ServiceException;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

public class ClosedTicketGenerator extends AbstractTicketGenerator {

    public ClosedTicketGenerator(ReportEngine reportEngine, TemplateStore templateStore) {
        super(reportEngine, templateStore);
    }

    public void generate() throws IOException, ServiceException {
        System.out.println("generate");
        final StringBuilder s1 = new StringBuilder();
        final String temp1 = templateStore.get("tickets_closed_Group");
        final String temp2 = templateStore.get("tickets_closed_Group_Item");

        doWithTickets(new TicketJob() {
            @Override
            public void execute(Group group, List<Ticket> tickets) throws ServiceException {
                StringBuilder s2 = new StringBuilder();
                tickets = reportEngine.getClosedTickets(tickets);
                for(Ticket ticket : tickets) {
                    s2.append(reportEngine.replaceWithTicket(temp2, ticket));
                }
                if (tickets.size() > 0) {
                    s1.append(replaceGroup(temp1, group, s2));
                }
            }
        });

        FileUtils.writeStringToFile(new File("./tmp/out/punkte_erledigt.html"),
                templateStore.get("tickets_closed_Main")
                        .replace("${Group}", s1)
                        .replace("${date}", format.format(new Date()))
                        .replace("${title}", "Erledigte Punkte")
        );
    }

}
